<?php
/**
 * api输出
 * 
 * @author: xudawei@staff.139.com
 * @copyright 139.com Inc
 * 
 */

class ApiEcho {

	function _createXml($array, $root_note) {
		$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<$root_note>";
		$xml .= self::_array2xml($array);
		$xml .= "\n</$root_note>";
		return $xml;
	}

	/**
	 * 数组转换为xml
	 * @param array $array
	 */
	static public function _array2xml($array) {
		static $i = 0;//用于xml输出缩进
		foreach($array as $key=>$val) {
			$num = is_numeric($key);

			if ($num) {
				$key = "item";
				$i = 0;
			}

			$pad = str_repeat("  ", $i);
			$xml .= "\n$pad<$key>";

			if (is_array($val)) {
				$nei_key = $key;
				$i++;
				$xml .= self::_array2xml($val);
			}else{
				$xml .= htmlspecialchars($val, ENT_NOQUOTES);
			}

			if (!$num && $key == $nei_key) {
				$xml .= "\n$pad</$key>";
				$i--;
			}else{
				$num || $xml .= "</$key>";
			}

			$num && $xml .= "\n</item>";
		}
		return $xml;
	}

	/**
	 * 输出XML
	 * @param array $array_data
	 * @param string $api_method
	 */
	static public function RenderXml($array_data, $api_method) {
		if (isset($array_data['error_code'])) {
			$api_method = 'hash';
		}
		return self::_createXml($array_data, $api_method);
	}

	/**
	 * 输出json
	 * @param array $array_data
	 * @return string
	 */
	static public function RenderJson($array_data){
		return json_encode($array_data);
		/*
		array_walk_recursive($array_data, 'ApiUtility::rUrlencode');
		$ret = urldecode(json_encode($array_data));
		return $ret;
		*/
	}

	/**
	 * 输出标准oauth返回格式
	 * @param array $array_data
	 * @param string $api_method
	 */
	static public function RenderOauthRet($array_data, $api_method) {
		if ($api_method == 'oauth_request_token' || $api_method == 'oauth_access_token') {
			$ret_str = '';
			foreach ($array_data as $k => $v) {
				$ret_str .= '&' . $k . '=' . urlencode($v);
			}
			return substr($ret_str, 1);
		} else {
			return self::RenderJson($array_data);
		}

	}
}
